package com.yqya.springboot.pattern.strategy.biz.handler;

import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.yqya.springboot.pattern.strategy.annotations.OrderHandlerType;

/**
 * 启动扫描订单处理器handler入口
 *
 * @author Kevin
 * @date 2019-06-29
 */
@Component
public class OrderHandlerProcessor implements BeanFactoryPostProcessor {

    private static final String ORDER_HANDER_PACKAGE = "com.yqya.springboot.pattern.strategy.biz.handler.impl";

    /**
     * 扫描@OrderHandlerType，初始化HandlerContext，将其注册到spring容器
     *
     * @param beanFactory
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        Map<String, Class> orderHandlerMap = Maps.newHashMapWithExpectedSize(3);
        Set<Class<?>> clazzList = ClassScaner.scan(ORDER_HANDER_PACKAGE, OrderHandlerType.class);
        for (Class clazz : clazzList) {
            OrderHandlerType orderHandlerType = (OrderHandlerType) clazz.getAnnotation(OrderHandlerType.class);
            String type = orderHandlerType.value();
            orderHandlerMap.put(type, clazz);
        }
        OrderHandlerContext context = new OrderHandlerContext(orderHandlerMap);
        beanFactory.registerSingleton(OrderHandlerContext.class.getName(), context);
    }

}
